# Importing Data
SWEDEN <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/UAE/Sweden.xlsx")

# Checking the Imported Data
View(SWEDEN)

# Creating Time Series Data
SWEDEN_ts <- ts(SWEDEN, start=c(2004,01), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
SWEDEN_ts
sum(is.na(SWEDEN_ts))
library(forecast)
SWEDEN_ts <- tsclean(SWEDEN_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(SWEDEN_ts)
plot(aggregate(SWEDEN_ts,FUN=mean))

# Decomposing
SWEDEN_ts_decomp <- decompose(SWEDEN_ts)
plot(SWEDEN_ts_decomp)

# Testing for Stationarity
acf(SWEDEN_ts, lag.max=20)
pacf(SWEDEN_ts, lag.max=20)

# To see any seasonal effect
boxplot(SWEDEN_ts~cycle(SWEDEN_ts))

# To remove trend effect
SWEDEN_ts_diff <- diff(SWEDEN_ts)
plot(SWEDEN_ts_diff)

# To remove variance effect
SWEDEN_ts_log <- log(SWEDEN_ts)
plot(SWEDEN_ts_log)

# To remove both (Trend and Variance) effects
SWEDEN_ts_both <- diff(log(SWEDEN_ts))
plot(SWEDEN_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(SWEDEN_ts, lag.max=20)
acf(log(SWEDEN_ts), lag.max=20)
acf(diff(SWEDEN_ts), lag.max=20)
acf(diff(log(SWEDEN_ts)), lag.max=20)
pacf(SWEDEN_ts, lag.max=20)
pacf(log(SWEDEN_ts), lag.max=20)
pacf(diff(SWEDEN_ts), lag.max=20)
pacf(diff(log(SWEDEN_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
SWEDEN_ts_model <- auto.arima(SWEDEN_ts)
SWEDEN_ts_model
SWEDEN_ts_model <- auto.arima(SWEDEN_ts, ic="aic", trace = TRUE)
SWEDEN_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(SWEDEN_ts_model$resid)
acf(SWEDEN_ts_model$residuals, main='ACF Residual')
pacf(SWEDEN_ts_model$residuals, main='ACF Residual')
Box.test(SWEDEN_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
SWEDEN_ts_forecast <- forecast (SWEDEN_ts_model, level=c(95), h=258)
plot(SWEDEN_ts_forecast)
SWEDEN_ts_forecast             


write.table(SWEDEN_ts_forecast, file="Sweden_TSA.csv", sep=",")
